package cn.liuweiwei.aspect;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class LogAspect {

    private static final ResultLog resultLog = new ResultLog();

    @Pointcut("execution(* cn.liuweiwei.controller.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        resultLog.setUrl(request.getRequestURL().toString());
        resultLog.setIp(request.getRemoteAddr());
        resultLog.setClassName(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        resultLog.setArgs(joinPoint.getArgs());
        log.warn("{}", resultLog);
    }

    @AfterReturning(returning = "result", pointcut = "log()")
    public void afterReturn(Object result) {
        log.warn("{}", result);
    }

    @Data
    private static class ResultLog {
        private String url;
        private String ip;
        private String className;
        private Object[] args;
    }

}
